﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Autofac;

namespace zDit.Core
{
    public interface ILifetimeScopeProvider
    {
        ILifetimeScope GetLifetimeScope(Action<ContainerBuilder> configurationAction);
    }
    public class AutofacGenericLifetimeScopeProvider : ILifetimeScopeProvider
    {
        private readonly ILifetimeScope _container;
        public static readonly object HttpRequestTag = "AutofacWebRequest";
        private static ILifetimeScope LifetimeScope
        {
            get;
            set;
        }
        public ILifetimeScope ApplicationContainer
        {
            get
            {
                return this._container;
            }
        }

        public AutofacGenericLifetimeScopeProvider(ILifetimeScope container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            this._container = container;
        }
        public ILifetimeScope GetLifetimeScope(Action<ContainerBuilder> configurationAction)
        {
            if (LifetimeScope == null && (LifetimeScope = this.GetLifetimeScopeCore(configurationAction)) == null)
            {
                throw new InvalidOperationException(base.GetType().FullName);
            }
            return LifetimeScope;
        }
        protected virtual ILifetimeScope GetLifetimeScopeCore(Action<ContainerBuilder> configurationAction)
        {
            if (configurationAction != null)
            {
                return this.ApplicationContainer.BeginLifetimeScope(HttpRequestTag, configurationAction);
            }
            return this.ApplicationContainer.BeginLifetimeScope(HttpRequestTag);
        }
    }
}
